import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { DNavBar, DModal } from '@/components'
import DHeader from './component/header'
import DContent from './component/content'
import DList from './component/list'
import DFooter from './component/footer'
import classNames from 'classnames'
import http from '@/api'
import sdk from '@/common/sdk'
import dayjs from 'dayjs'
import './itemdetail.scss'
const conf = require('../../../config/conf')

class DSaledetail extends Component {

  constructor(props) {
    super(props)
    this.state = {
      bgImages: require('../assets/bgImages.png'),
      title: "售车订单",
      headerobj: {
        itemtime: {
          isShowDay: false,
          isShowHour: false,
          day: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        }
      },
      isShow: false,
      item: {},
      crmodal: '',
      modal1: '',
      id: '',
      firstList: {
        info: [
          {
            label: "买家名称",
            value: ""
          },
          {
            label: "买家联系人",
            value: ""
          },
          {
            label: "买家联系方式",
            value: ""
          }
        ]
      },
      status: '',
      secondList: {
        title: "车辆信息",
        info: [
          {
            label: "交易车型",
            value: ""
          },
          {
            label: "车源类型",
            value: ""
          },
          {
            label: "车辆指导价",
            value: ""
          },
          {
            label: "外观颜色",
            value: ""
          },
          {
            label: "内饰颜色",
            value: ""
          },
          {
            label: "排放标准",
            value: ""
          }
        ]
      },
      threeList: {
        title: "交易信息",
        info: [
          {
            label: "成交数量",
            value: ""
          },
          {
            label: "成交总价",
            value: ""
          },
          {
            label: "订金金额",
            value: ""
          }
        ]
      },
      dlist: {
        list: [
          {
            title: '合同凭证'
          }
        ]
      }


    }
  }

  componentWillMount() {
    let { id, status } = this.$router.params
    this.setState({
      status,
      id,
      headerobj: {
        title: this.getStatus(status)
      }
    })
    this.getDetailList(id)
  }

  componentDidShow() {
    sdk.setTitleInfo(this.state.title)
  }

  getDetailList(id) {
    let { firstList, secondList, threeList } = this.state
    http.getSaleDetail(id).then(res => {
      if (!res) {
        return
      }
      if (res.orStatus !== this.$router.params.status) {
        Taro.showToast({
          title: '订单状态已更新',
          icon: 'none'
        }).then(date => {
          Taro.redirectTo({
            url: `/pages/itemdetail/shopdetail?id=${res.id}&status=${res.orStatus}`
          })
        })
      }
      // 单位配对
      function getPrice(i) {
        return {
          $0: '台',
          $1: '万元',
          $2: '元'
        }[`$${i}`]
      }

      let _firstList = ['entName', 'creator', 'creatorContact']
      firstList.info.map((item, i) => {
        item.value = res[_firstList[i]]
      })

      let _secondList = ['orCarModel', 'orCarSourceType', 'orCarGuiPrice', 'orCarOutColor', 'orCarInColor', 'orCarEmissionStd']
      secondList.info.map((item, i) => {
        item.value = res[_secondList[i]] + (i === 2 ? getPrice(1) : '')
      })

      let _threeList = ['orCount', 'orTotalPrice', 'orEarnestPrice']
      threeList.info.map((item, i) => {
        item.value = res[_threeList[i]] + getPrice(i)
      })

      //根据订单状态计算倒计时
      let orStatus = this.$router.params.status
      let times = '', minutes = 0
      // res.updateTime = '2021-01-04 18:05'
      if (orStatus === '21') {
        let createTime = dayjs(res.updateTime).add(30, 'minute')
        times = createTime.diff(dayjs(), 'day', 'true')
        // minutes = createTime.diff(dayjs(), 'minute', 'true')
      } else if (orStatus === '32') {
        let createTime = dayjs(res.updateTime).add(3, 'day')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else {
        times = 0
      }
      this.setState({
        firstList,
        secondList,
        threeList,
        item: res,
        headerobj: {
          ...this.state.headerobj,
          account: res.orNo,
          text: this.getText(this.$router.params.status),
          tiptext: this.getPlatformTxt(this.$router.params.status),
          itemtime: {
            isShowDay: false,
            isShowHour: true,
            day: times,
            hours: 0,
            minutes,
            seconds: 0
          }
        }
      })
    })
  }
  getStatus(status) {
    return {
      $21: `待接单`,
      $31: `待上传`,
      $32: `待买家确认`,
      $33: `待核实`,
      $41: `交易成功`,
      $42: `已拒接`,
      $43: `已撤回`,
      $44: `已超时`,
      $45: `交易异常`,
      $49: `待退款`,
    }[`$${status}`]
  }
  getPlatformTxt(orstatu) {
    return {
      $21: '系统将自动拒绝接单',
      $32: '将自动确认',
      // $33: '将自动确认',
    }[`$${orstatu}`]
  }
  getText(orstatu) {
    return {
      $21: '请确认消息以及是否接单',
      $31: '请在交易完成后上传相关合同及凭证',
      $32: '买家正在核实订单，请耐心等候',
      $33: `平台将在<text style='font-size:20px;font-weight:bold;color:#FFAE00'>5</text>日内核实订单，逾时将自动确认`,
      $41: '亲，恭喜你成功完成一笔订单！企业管理员可提现订金',
      $42: '该订单已拒接',
      $44: '该订单已超时',
      $43: '很遗憾，买家已取消订单',
      $45: '您的订单交易异常，平台客服已介入并终止',
      $49: '买家申请退款',
    }[`$${orstatu}`]
  }

  hanleFirst(status) {
    let isShow = true
    this.setState({
      isShow,
      crmodal: status,
      modal1: '您确认拒绝接受订单吗？'
    })
  }

  refuseSaleOrder(orderId) {
    http.refuseSaleOrder2({ orderId: orderId }).then((res) => {
      // 刷新页面
      window.location.reload();
    })
  }

  handleLast(status) {
    if (this.state.headerobj.itemtime.day <= 0) {
      return Taro.showToast({
        title: '订单超时,系统已经自动拒绝接单',
        icon: "none"
      })
    }
    let isShow = true
    this.setState({
      isShow,
      crmodal: status,
      modal1: '您确认接受订单吗？'
    })
  }

  confirmSaleOrder(orderId) {
    http.acceptSaleOrder({ orderId: orderId }).then((res) => {
      if (!res) {
        return
      }
      Taro.redirectTo({
        url: `/pages/itemdetail/saledetail?id=${orderId}&status=31`
      })
    })
  }

  onClose() {
    this.setState({
      isShow: false
    })
  }

  onLastHandle() {
    let { crmodal, item } = this.state
    this.onClose()
    if (crmodal === '1') {
      this.refuseSaleOrder(item.id)

    } else if (crmodal === '2') {
      this.confirmSaleOrder(item.id)
    }
  }

  handleContact() {
    let { id } = this.state
    Taro.navigateTo({
      url: `/pages/contractproof/contractproof?id=${id}&status=1`
    })
  }
  hanleFirst1() {
    const { id } = this.state
    http.clcgTemplate(id).then((res, urls) => {
      // 下载合同接口
      const a = document.createElement('a');


      const url = URL.createObjectURL(res);
      const filename = '车辆采购合同下载.zip';
      a.href = url;
      a.download = filename;
      a.click();
    })
  }
  handleLast1() {
    const { id } = this.state
    Taro.redirectTo({
      url: `/pages/caruploadinfo/caruploadinfo?id=${id}`
    })
  }
  render() {
    const {
      bgImages,
      title,
      firstList,
      secondList,
      threeList,
      headerobj,
      isShow,
      status,
      dlist,
      modal1,
      infoData,
      bodyData,
      signData,
    } = this.state
    return (
      <View className='b_itemdetail'>
        <Image src={bgImages} className={classNames('b_itemdetail__imagebs', process.env.NODE_ENV === 'development' ? '' : 'b_itemdetail__NODEimg')}></Image>
        <DNavBar title={title} className='b_itemdetail__nav'></DNavBar>
        <View className='b_itemdetail__box'>
          <View className='b_itemdetail__content'>
            <DHeader {...headerobj}></DHeader>
            <DContent {...firstList}></DContent>
            <DContent {...secondList}></DContent>
            <DContent {...threeList}></DContent>
            {status > 31 && status < 42 &&
              <DList {...dlist} handleClick={this.handleContact.bind(this)}></DList>
            }
            {status === '21' &&
              <DFooter firstText='拒绝接单' onFirstClick={this.hanleFirst.bind(this, '1')} secondText='确认接单' onSeconClick={this.handleLast.bind(this, '2')}></DFooter>
            }
            {status === '31' &&
              <DFooter onFirstClick={this.hanleFirst1.bind(this)} secondText='上传资料' onSeconClick={this.handleLast1.bind(this)}></DFooter>
            }
          </View>
        </View>
        <DModal
          isShow={isShow}
          title='提示'
          text={modal1}
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>

        {/* 跳转龙存管页面 */}
        <form action={conf.fromURL} method="post">
          <input type="hidden" name="INFO" value={infoData} />
          <input type="hidden" name="CONTENTTYPE" value="json" />
          <input type="hidden" name="charset" value="GBK" />
          <input type="hidden" name="BODY" value={bodyData} />
          <input type="hidden" name="SIGN" value={signData} />
          <input type="submit" ref="submit" value="Submit" style={{ opacity: 0, width: 0, height: 0 }} />
        </form>
      </View>
    )
  }

}


export default DSaledetail
